/**
 * @author Praveen Krupakaran (A0092625)
 */
package sg.edu.nus.iss.team4ft.ui;

import java.awt.GridLayout;
import java.awt.Panel;
import java.util.ArrayList;

import sg.edu.nus.iss.team4ft.service.Account;
import sg.edu.nus.iss.team4ft.service.Plan;
import sg.edu.nus.iss.team4ft.service.PlanCode;

public class AccountControl extends Panel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Account account;
	private Mode mode;
	private ArrayList<PlanControl> planControl = new ArrayList<PlanControl>();
	
	public AccountControl(Mode mode, Account account) throws Exception{
		this.setAccount(account);
		setMode(mode);
		loadControls(mode, account);
		
	}

	private void loadControls(Mode mode, Account account) throws Exception {
		this.setPreferredSize(new java.awt.Dimension(650, 800));
		loadPlan();	
		Panel p = new Panel(new GridLayout(3,1));
		for (PlanControl pc : planControl) {
			p.add(pc);
		}
		
		p.setVisible(true);
		this.add(p);		
	}

	private void loadPlan() throws Exception {
		PlanControl digitalVoice, mobileVoice, channelService;
		Plan dv = null, mv = null,cs = null;
		
		if(account != null){
			dv = account.getPlan(PlanCode.DigitalVoice);
			mv = account.getPlan(PlanCode.MobileVoice);
			cs = account.getPlan(PlanCode.CableTV);
		}
		
		if(dv != null && dv.getEndDate() == null)
			digitalVoice = new PlanControl(dv, mode);
		else
			digitalVoice = new PlanControl(PlanCode.DigitalVoice, mode);
		
		if(mv != null && mv.getEndDate() == null)
			mobileVoice = new PlanControl(mv, mode);
		else
			mobileVoice = new PlanControl(PlanCode.MobileVoice, mode);
		
		if(cs != null  && cs.getEndDate() == null)
			channelService = new PlanControl(cs, mode);
		else
			channelService = new PlanControl(PlanCode.CableTV, mode);
		
		digitalVoice.setVisible(true);
		mobileVoice.setVisible(true);
		channelService.setVisible(true);
		
		planControl.add(digitalVoice);
		planControl.add(mobileVoice);
		planControl.add(channelService);
		
	}
	
	public boolean isValidToSave(){
		boolean isValid = true;
		for (PlanControl pc : planControl) {
			if(!pc.isValid())
				isValid = false;
		}
		return isValid;					
	}

	public Mode getMode() {
		return mode;
	}

	public void setMode(Mode mode) {
		this.mode = mode;
	}

	public Account getAccount() throws Exception {
		if(account == null)
			account = new Account();
		
		for (PlanControl pc : planControl) {
			Plan p = pc.getPlan();
			if(p != null)
				account.subscripeNewPlan(p);
		}
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}
}
